<?php
namespace app\push\logic;

use app\common\logic\TronLogic;
use fast\AipHttpClient;
use think\Db;
use think\Queue;

/**
 * 编码环境win10  php7.3 linux请注意目录大小写的区分
 * 如果你觉得代码不错 对您的项目有帮助 谢谢你的使用 我的地址：TKauo6SnhLNyTDvkVByR13cR7S5xnq3yT4
 * Class Trc20Logic
 * @package app\push\logic
 */
class Trc20Logic
{
    /**
     * 合约地址
     * @var string
     */
    private $USDT_ADDRESS = "TMuvMdGYH8mcfRNQZrHGNss6mXPFxqmKWC";

    private $HEADER = [
        "Content-Type"=> "application/json",
        "TRON-PRO-API-KEY"=> "664960e3-844d-4e37-b288-90f3faa87be3"
    ];


    /**
     *TRC20-USDT 充币监听
     * @param $projectId
     */
    public function checkTransaction($projectId){
        $tronLogic = new TronLogic();
        Db::name('trc_address')
            ->where('project_id',$projectId)
            ->chunk(100, function ($data) use ($tronLogic) {
                foreach ($data as $datum) {
                    $address = $datum['address'];
                    $last_block_number_timestamp = $datum['usdt_last_block_number_timestamp'] + 1000;
                    $result = $tronLogic->trc20TransactionsList($address,"LK", $last_block_number_timestamp);
                    if ($result['code'] != 200) continue;

                    $content = jsonDecode($result['content']);
                    $contentData = $content['data'];
                    if (empty($contentData)) continue;

                    Db::transaction(function () use ($contentData, $datum){
                        $u = 0; // 本次查到的累计金额
                        foreach ($contentData as $contentDatum) {
                            $amount = $contentDatum['value'] / 10**6;
                            // 记录交易
                            Db::name('trc_transaction')
                                ->insert([
                                    "project_id" => $datum['project_id'],
                                    "from"       => $contentDatum['from'],
                                    "to"         => $contentDatum['to'],
                                    "amount"     => $amount,
                                    "transaction_id" => $contentDatum['transaction_id'],
                                    "block_timestamp" => $contentDatum['block_timestamp'],
                                    "data"  => jsonEncode($contentDatum),
                                    "insert_time" => date('Y-m-d H:i:s')
                                ]);
                            // 是否在这里推送交易信息到第三方去


                            // 累计金额
                            $u += $amount;
                        }
                        // 更新账户余额和usdt_last_block_number_temstamp
                        Db::name('trc_address')
                            ->where('id',$datum['id'])
                            ->update([
                                'usdt_last_block_number_timestamp' => $contentData[0]['block_timestamp'],
                                'usdt' => Db::raw("usdt+{$u}"),
                                'is_collect' => 0,
                                'updatetime' => time()
                            ]);
                    });
                }
        },'id','asc');
    }

    /**
     * 归集
     * @param $projectId
     */
    public function collection($projectId){
        $tronLogic = new TronLogic();
        Db::name('trc_address')
            ->where('project_id',$projectId)
            ->where('is_collect',0)
            ->where('usdt','>' , 0)
            ->chunk(100, function ($data) use ($tronLogic) {
                foreach ($data as $datum) {
                    $address = $datum['address'];
                    $private_key = $datum['private_key'];
                    $symbol = "LK";
                    $result = $tronLogic->collectionTrc20($address,$private_key,$symbol);
                    if ($result['status'] == -1) continue;

                    if ($result['status'] == 0){
                        $queueClassName = "app\\job\\Task@collection";
                        $queueName = "Trc20CollectionQueue";
                        Queue::push($queueClassName,['address' => $address,'private_key' => $private_key,'symbol'=>$symbol],$queueName);
                    }


                    if ($result['status'] == 1){
                        Db::transaction(function () use ($address){
                            Db::name("trc_address")
                                ->where('address',$address)
                                ->update([
                                    'is_collect' => 1,
                                    'usdt' => 0,
                                    'updatetime' => time()
                                ]);
                        });
                    }

                }
            },'id','asc');
    }
}